import axios from 'axios'
import { baseURL } from '@/config/baseURL'
import { useUserStore } from '@/store/user'

const instance = axios.create({
  baseURL: baseURL,
  timeout: 1000,
})

instance.interceptors.request.use((config) => {
  const authStore = useUserStore()
  if (authStore.token) {
    config.headers.Authorization = authStore.token
    // config.headers.token = authStore.token
  }
  return config
})
instance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      const authStore = useUserStore()
      authStore.clearToken()
      // router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath))
    }
    return Promise.reject(error)
  },
)

export const $get = async (url: string, params?: object) => {
  const { data } = await instance.get(url, { params })
  return data
}

export const $post = async (url: string, params?: object) => {
  const { data } = await instance.post(url, params)
  return data
}
